<template>

	<basic-container style="display: flex; flex-wrap:wrap;">
		<div :style="DEBUG?'width: 70%;float: left;':'width: 100%;float: left;'">
			<span class="demonstration">DI</span>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="6" v-for="(detail,index) in DIData" v-bind:key="index">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">{{detail.name}}
					</el-tag>
					<el-switch disabled v-model="detail.value" :active-text='$t("wel.table.HighLevel")'
						:inactive-text='$t("wel.table.LowLevel")'>
					</el-switch>
				</el-col>
			</el-row>


			<span class="demonstration">DO</span>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="6" v-for="(detail,index) in DOData" v-bind:key="index">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">{{detail.name}}
					</el-tag>
					<el-switch v-model="detail.value" :active-text='$t("wel.table.HighLevel")'
						:inactive-text='$t("wel.table.LowLevel")' @change="DOChange($event,detail)">
					</el-switch>

				</el-col>
			</el-row>

			<span class="demonstration">AI</span>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="6" v-for="(detail,index) in AIData" v-bind:key="index">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">{{detail.name}}
					</el-tag>
					<el-tag type="info" effect="dark" style="margin-right: 20px;width: 80px;">{{detail.value}}
					</el-tag>
				</el-col>
			</el-row>

			<span class="demonstration">PWM</span>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="6" v-for="(detail,index) in PWMData" v-bind:key="index">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">{{detail.name}}
					</el-tag>
					<el-switch v-model="detail.value" :active-text="$t('wel.table.Open')"
						:inactive-text="$t('wel.table.Close')" @change="PWMChange($event,detail)">
					</el-switch>

				</el-col>
			</el-row>


			<span class="demonstration">UART</span>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="24">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">UART1</el-tag>
					<textarea
						style="background-color: #000000;border-radius: 0.625rem;padding: 0.625rem;color: #FFFFFF;margin-left:2rem;"
						disabled cols="60" rows="10" v-model="UartOneList"></textarea>
					<textarea
						style="background-color: #FFFFFF;border-radius: 0.625rem;padding: 0.625rem;color: #000000;margin-left:2rem;"
						cols="60" rows="10" v-model="UartOneText"></textarea>
					<el-button type="primary" @click="sendUart(0)" style="width: 10%;margin-left: 0.3125rem;">
						{{$t('wel.table.send_out')}}
					</el-button>
				</el-col>
			</el-row>
			<el-row :gutter="24" style="margin-bottom: 30px;margin-top: 20px;">
				<el-col :span="24">
					<el-tag type="success" effect="dark" style="margin-right: 20px;width: 80px;">UART2</el-tag>
					<textarea
						style="background-color: #000000;border-radius: 0.625rem;padding: 0.625rem;color: #FFFFFF;margin-left:2rem;"
						disabled cols="60" rows="10" v-model="UartTwoList"></textarea>
					<textarea
						style="background-color: #FFFFFF;border-radius: 0.625rem;padding: 0.625rem;color: #000000;margin-left:2rem;"
						cols="60" rows="10" v-model="UartTwoText"></textarea>
					<el-button type="primary" @click="sendUart(1)" style="width: 10%;margin-left: 0.3125rem;">
						{{$t('wel.table.send_out')}}
					</el-button>
				</el-col>
			</el-row>
		</div>
		<div :style="DEBUG?'width:25%;float:left':'width:0%;float:left'" v-if="DEBUG">
			<textarea
				style="background-color: #000000;border-radius: 0.625rem;padding: 0.625rem;color: #FFFFFF;margin-left:2rem;"
				disabled cols="60" rows="30" v-model="logText"></textarea>
			<el-input v-model="sendTheme" style="margin-left:2rem;margin-top: 1.25rem;" disabled />
			<textarea
				style="background-color: #FFFFFF;border-radius: 0.625rem;padding: 0.625rem;color: #000000;margin-left:2rem;margin-top: 1.25rem;"
				cols="60" rows="10" v-model="sendTextMessage"></textarea>
			<el-button type="primary" @click="sendText()" style="margin-left: 1.875rem;margin-top: 1.25rem;">
				{{$t('wel.table.send_out')}}
			</el-button>
		</div>
	</basic-container>


</template>

<script>
	import mqtt from 'mqtt'
	import {
		mapGetters
	} from "vuex";
	import request from '@/router/axios';
	import {
		DEBUG,
		baseUrl,
		MQTT_SERVICE,
		MQTT_USERNAME,
		MQTT_PASSWORD
	} from '@/config/env';


	var client;
	var clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)

	const options = {
		connectTimeout: 40000,
		clientId: "user" + clientId,
		username: MQTT_USERNAME,
		password: MQTT_PASSWORD,
		clean: true
	}


	export default {
		name: "wel",

		data() {
			return {
				sendTheme: "",
				id: 0,
				UartOneList: "",
				UartOneText: "",
				UartTwoList: "",
				UartTwoText: "",
				isLoadding: false,
				clientStatus: false,
				loading: null,
				DIData: [],
				AIData: [],
				DOData: [],
				PWMData: [],
				dic: [],
				device: {},
				searchText: "",
				data: [],
				type: '',
				box: false,
				formList: [],
				configform: {},
				option: {
					submitBtn: false,
					emptyBtn: false,
					column: [],
				},
				logText: "",
				sendTextMessage: "",
			};
		},
		computed: {

		},
		created() {
			let param = this.$route.query;
			this.id = param.id;

			this.getDevice();
		},
		methods: {
			sendText() {
				client.publish(this.sendTheme, this.sendTextMessage);
			},

			//发送UART数据
			sendUart(index) {
				let text = index == 0 ? this.UartOneText : this.UartTwoText;
				console.log(text);
				let num = index;
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/sendUARTData',
						data: {
							id: that.device.id,
							num: num,
							text: text,
						}
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							//设置为正在等待响应状态
							if (num == 0) {
								that.UartOneList = that.UartOneList + "↓  " + text + "\r\n";
							} else {
								that.UartTwoList = that.UartTwoList + "↓  " + text + "\r\n";
							}
							that.isLoadding = true;
							that.loadding();
							//that.$message.success(response.data.info);
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$
					})
			},
			getUserinfo() {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/user/userinfo',
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.userInfo = response.data.data;
							// mqtt连接

							that.mqttMSG();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},

			mqttMSG() {
				let that = this;
				console.log("准备连接MQTT");
				console.log("连接状态：", this.clientStatus);
				if (!this.clientStatus) {
					options.clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)
					client = mqtt.connect(MQTT_SERVICE, options)
				}
				client.on('connect', (e) => {
					this.clientStatus = true;
					console.log('连接成功:', that.device)
					//监听设备上传信息
					this.sendTheme = "all/" + that.device.code + "/sub",
						client.subscribe('user/' + that.userInfo.id + "/" + that.device.code, {
							qos: 1
						}, (error) => {
							if (!error) {
								console.log('订阅成功')
							} else {
								console.log('订阅失败')
							}
						})
					//监听所有消息
					if (DEBUG) {
						client.subscribe('all/' + that.device.code + "/#", {
							qos: 1
						}, (error) => {
							if (!error) {
								console.log('订阅成功')
							} else {
								console.log('订阅失败')
							}
						})
					}
				})
				// 接收消息处理
				client.on('message', (topic, message) => {
					var data = JSON.parse(message)
					let that = this;
					let deviceMessage = ["getAIStatusRsp", "postSysInfo", "reqSysInfoRsp", "cfgSysParamsRsp",
						"keepAlive", "cfgDOParamsRsp", "reqDOParamsRsp",
						"setDOStatusRsp", "getDOstatusRsp", "cfgDIParamsRsp", "reqDIParamsRsp",
						"getDIstatusRsp", "postDIInfo", "cfgAIParamsRsp", "reqAIParamsRsp",
						"getAIstatusRsp", "cfgPWMParamsRsp", "reqPWMParamsRsp", "setPWMStatusRsp",
						"getPWMstatusRsp", "cfgUARTParamsRsp", "reqUARTParamsRsp", "revUARTData"
					];
					let userMessage = ["reqSysInfo", "cfgSysParams", "getSysParams", "getSysParamsRsp",
						"cfgDOParams", "reqDOParams", "setDOStatus", "getDOStatus", "cfgDIParams",
						"reqDIParams", "getDIStatus", "cfgAIParams", "reqAIParams", "getAIStatus",
						"cfgPWMParams", "reqPWMParams", "setPWMStatus", "getPWMStatus", "cfgUARTParams",
						"reqUARTParams", "sendUARTData", "reboot", "reload"
					]
					let reqList = ['setDOStatusRsp', 'postDIInfo', 'getAIStatusRsp', 'setPWMStatusRsp',
						'revUARTData'
					];
					if (data.type === "setDOStatusRsp") {
						data.params.forEach(function(item, index) {
							that.DOData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.value = item.value === 1 ? true : false;
								}
							})
						})
					} else if (data.type === "postDIInfo") {
						data.params.forEach(function(item, index) {
							that.DIData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.value = item.value === 1 ? true : false;
								}
							})
						})
					} else if (data.type === "getAIStatusRsp") {
						data.params.forEach(function(item, index) {
							that.AIData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.value = item.value;
								}
							})
						})
					} else if (data.type === "setPWMStatusRsp") {
						data.params.forEach(function(item, index) {
							that.PWMData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.value = item.status === 1 ? true : false;
								}
							})
						})
					} else if (data.type === "revUARTData") {
						if (data.params.num == 0) {
							this.UartOneList = this.UartOneList + "↑  " + data.params.message + "\r\n";
						} else {
							this.UartTwoList = this.UartTwoList + "↑  " + data.params.message + "\r\n";
						}
					}
					if (deviceMessage.indexOf(data.method) != -1) {
						this.logText = this.logText + "↑  消息主题    " + topic + "\r\n";
						this.logText = this.logText + "   消息内容    " + JSON.stringify(data) + "\r\n\r\n";
					} else if (userMessage.indexOf(data.method) != -1) {
						this.logText = this.logText + "↓  消息主题    " + topic + "\r\n";
						this.logText = this.logText + "   消息内容    " + JSON.stringify(data) + "\r\n\r\n";
					}


					if (that.isLoadding === true && that.loading !== null && reqList.indexOf(data.type) !== -1) {
						that.isLoadding = false;
						that.loading.close();
					}
				})
				// 断开发起重连
				client.on('reconnect', (error) => {
					console.log('正在重连:', error)
				})
				// 链接异常处理
				client.on('error', (error) => {
					console.log('连接失败:', error)
				})
			},

			DOChange(from, detail) {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/DOSetting',
						data: detail
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							//设置为正在等待响应状态
							that.isLoadding = true;
							that.loadding();
							//that.$message.success(response.data.info);
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			PWMChange(from, detail) {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/PWMSetting',
						data: detail
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							//设置为正在等待响应状态
							that.isLoadding = true;
							that.loadding();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			getDevice() {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/getDeviceDetail',
						data: {
							id: that.id
						}
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.device = response.data.data.detail;
							console.log(that.device);
							//DI显示
							response.data.data.DI.forEach(function(item, index) {
								item.value = item.value === "1" ? true : false;
								that.DIData.push(item);
							})
							response.data.data.DO.forEach(function(item, index) {
								item.value = item.value === "1" ? true : false;
								that.DOData.push(item);
							})
							response.data.data.AI.forEach(function(item, index) {
								item.value = item.value;
								that.AIData.push(item);
							})
							response.data.data.PWM.forEach(function(item, index) {
								item.value = item.value === "1" ? true : false;
								that.PWMData.push(item);
							})
							that.getUserinfo();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			loadding() {
				this.loading = this.$loading({
					lock: true,
					text: this.$t("wel.table.loadding"),
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				setTimeout(() => {
					if (this.isLoadding) {
						this.loading.close();
						this.$message.error(this.$t("wel.table.timeOut"));
					}
				}, 10000);
			}
		}
	};
</script>

<style scoped="scoped" lang="scss">
	.demonstration {
		margin-left: 30px;
		font-size: 32px;
		margin-bottom: 30px;
		font-weight: 900;
	}

	.detail {
		margin-left: 30px;
		margin-right: 30px;
		margin-top: 30px;
		font-size: 20px;
		font-weight: 900;
	}
</style>
